<?php
/**
 * Created by 长毋相忘c.
 * 文件用途描述 :
 * Date: 2018/2/18/018
 * Time: 15:48
 */

namespace app\api\service;


use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\TokenException;
use think\Cache;
use think\Exception;
use think\Request;

class Token
{
    public static function generateToken(){
        //用三组字符串，进行MD5加密
        //32个字符自成一组随机字符串
        $randChar=getRandChar(32);
        //时间戳
        $timestamp=time();
        //salt 盐
        $salt=config('token_salt');
        return md5($randChar.$timestamp.$salt);
    }
//获取当前Token
    public static function getCurrentTokenVar($key){
        $token = Request::instance()->header('token');
        $vars = Cache::get($token);
        if (!$vars){
            throw new TokenException();
        }else{
            if (!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if (array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取Token变量并不存在');
            }
        }
    }

    //获取当前用户信息
    public static function getCurrentUid(){
        $uid=self::getCurrentTokenVar('uid');
        return $uid;
    }

    //用户和CMS都可以访问的权限
    public static function needPrimaryScope(){
        $scope=self::getCurrentTokenVar('scope');
        if($scope){
            if($scope >= ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }

    //只有用户能访问的权限
    public static function needExclusiveScope(){
        $scope=self::getCurrentTokenVar('scope');
        if($scope){
            if($scope == ScopeEnum::User){
                return true;
            }else{
                throw new ForbiddenException();
            }
        }else{
            throw new TokenException();
        }
    }

    /**
     * 函数用途描述 :检测传入的UID是否与令牌中的UID相同
     * @author: 孙洪亮
     * @param:  null
     * @return: null
     */
    public static function isValidOperate($checkedUID){
        if (!$checkedUID){
            throw new Exception('检查UID时必须传入一个被检测的UID');
        }
        $currentOperateUID = self::getCurrentUid();
        if ($currentOperateUID == $checkedUID){
            return true;
        }
        return false;
    }

    public static function verifyToken($token){
        $exist=Cache::get($token);
        if($exist){
            return true;
        }else{
            return false;
        }
    }


}